import axios from 'axios'
import { error } from 'console'

const baseURL = import.meta.env.VITE_BASE_API
const instance = axios.create({
  baseURL,
  timeout: 1000
})
//退出登录并强制刷新页面 重定向到登录页
const logout = () => {}
//添加请求拦截器
instance.interceptors.request.use(
  (config) => config,
  //发送失败
  (error) => Promise.reject(error)
)
//添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    const apiData = response.data
    const code = apiData.code
    switch (code) {
      case 0:
        return apiData
      //Token 过期
      case 401:
        return logout()
      default:
        // 不是正确code 提示
        // ElMessage.error(apiData.message || "Error")
        return Promise.reject(new Error('Error'))
    }
  },
  (error) => {
    const status = error.status
    switch (status) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        // Token 过期时
        logout()
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = '请求地址出错'
        break
      case 408:
        error.message = '请求超时'
        break
      case 500:
        error.message = '服务器内部错误'
        break
      case 501:
        error.message = '服务未实现'
        break
      case 502:
        error.message = '网关错误'
        break
      case 503:
        error.message = '服务不可用'
        break
      case 504:
        error.message = '网关超时'
        break
      case 505:
        error.message = 'HTTP 版本不受支持'
        break
      default:
        break
    }
    return Promise.reject(error)
  }
)
export default instance
